import { useState, useEffect } from 'react'
import Navbar from '../../compoents/Navbar'
import { useNavigate, useLocation } from 'react-router-dom'
import { Button } from 'antd-mobile'
import style from './index.module.css'

interface Report {
  id: number;
  title: string;
  type: string;
  typeColor: string;
  quantity: number;
}

interface ApplicationRecord {
  id: string
  title: string
  status: 'pending' | 'approved' | 'delivered' | 'cancelled'
  hospital: string
  applicant: string
  applicationTime: string
  orderAmount: number
  reports: Report[]
  reportQuantities: Record<number, number>
}

function Index() {
  const navigate = useNavigate()
  const location = useLocation()
  const [activeTab, setActiveTab] = useState('all')
  const [records, setRecords] = useState<ApplicationRecord[]>([])
  const userInfo = location.state?.userInfo || {}
  console.log('userInfo',userInfo,location.state);
  useEffect(() => {
    // 模拟数据，实际项目中应该从API获取
    const mockRecords: ApplicationRecord[] = [
      {
        id: '1',
        title: '门诊报告打印',
        status: 'pending',
        hospital: '四川省保健院北苑',
        applicant: '王小科',
        applicationTime: '2020-01-01 10:30:20',
        orderAmount: 17.00,
        reports: [],
        reportQuantities: {}
      },
      {
        id: '2',
        title: '门诊报告打印',
        status: 'approved',
        hospital: '四川省保健院北苑',
        applicant: '王小科',
        applicationTime: '2020-01-01 10:30:20',
        orderAmount: 17.00,
        reports: [],
        reportQuantities: {}
      },
      {
        id: '3',
        title: '门诊报告打印',
        status: 'delivered',
        hospital: '四川省保健院北苑',
        applicant: '王小科',
        applicationTime: '2020-01-01 10:30:20',
        orderAmount: 17.00,
        reports: [],
        reportQuantities: {}
      }
    ]

    // 从localStorage获取申请记录
    const savedRecords = localStorage.getItem('applicationRecords')
    if (savedRecords) {
      setRecords(JSON.parse(savedRecords))
    } else {
      setRecords(mockRecords)
    }
  }, [])

  // 如果有新的申请数据，添加到记录中
  useEffect(() => {
    if (location.state?.newApplication) {
      const newRecord: ApplicationRecord = {
        id: Date.now().toString(),
        title: '门诊报告打印',
        status: 'pending',
        hospital: '四川省保健院北苑',
        applicant: userInfo.name || '王小科', // 使用传递过来的用户姓名
        applicationTime: new Date().toLocaleString('zh-CN'),
        orderAmount: location.state.totalAmount || 0,
        reports: location.state.reports || [],
        reportQuantities: location.state.reportQuantities || {}
      }
      
      const updatedRecords = [newRecord, ...records]
      setRecords(updatedRecords)
      localStorage.setItem('applicationRecords', JSON.stringify(updatedRecords))
    }
  }, [location.state, records, userInfo.name])

  const tabs = [
    { key: 'all', label: '全部记录' },
    { key: 'pending', label: '待审核' },
    { key: 'approved', label: '已审核' },
    { key: 'cancelled', label: '已取消' }
  ]

  const getStatusInfo = (status: string) => {
    switch (status) {
      case 'pending':
        return { text: '待审核', className: 'statusPending' }
      case 'approved':
        return { text: '待寄出', className: 'statusApproved' }
      case 'delivered':
        return { text: '已寄出', className: 'statusDelivered' }
      case 'cancelled':
        return { text: '已取消', className: 'statusCancelled' }
      default:
        return { text: '未知', className: 'statusUnknown' }
    }
  }

  const getActionButton = (record: ApplicationRecord) => {
    switch (record.status) {
      case 'pending':
        return (
          <Button 
            className={style.cancelButton}
            onClick={() => handleCancelApplication(record.id)}
          >
            取消申请
          </Button>
        )
      case 'delivered':
        return (
          <Button 
            className={style.detailButton}
            onClick={() => handleViewDetails(record.id)}
          >
            查看详情
          </Button>
        )
      default:
        return null
    }
  }

  const handleCancelApplication = (id: string) => {
    const updatedRecords = records.map(record => 
      record.id === id ? { ...record, status: 'cancelled' as const } : record
    )
    setRecords(updatedRecords)
    localStorage.setItem('applicationRecords', JSON.stringify(updatedRecords))
  }

  const handleViewDetails = (id: string) => {
    const record = records.find(r => r.id === id)
    if (record) {
      // 将用户信息添加到记录中
      const recordWithUserInfo = {
        ...record,
        userInfo: userInfo
      }
      navigate('/OrderDet', { state: { record: recordWithUserInfo } })
    }
  }

  const filteredRecords = records.filter(record => {
    if (activeTab === 'all') return true
    return record.status === activeTab
  })

  return (
    <div className={style.container}>
      <Navbar showBack onBack={() => navigate(-1)} title="申请记录" />
      
      <div className={style.content}>
        {/* Tab导航 */}
        <div className={style.tabContainer}>
          {tabs.map(tab => (
            <div 
              key={tab.key}
              className={`${style.tabItem} ${activeTab === tab.key ? style.active : ''}`}
              onClick={() => setActiveTab(tab.key)}
            >
              {tab.label}
            </div>
          ))}
        </div>

        {/* 记录列表 */}
        <div className={style.recordsList}>
          {filteredRecords.map(record => {
            const statusInfo = getStatusInfo(record.status)
            return (
              <div key={record.id} className={style.recordCard}>
                <div className={style.cardHeader}>
                  <div className={style.titleSection}>
                    <div className={style.titleBar}></div>
                    <span className={style.title}>{record.title}</span>
                  </div>
                  <div className={`${style.statusTag} ${style[statusInfo.className]}`}>
                    {statusInfo.text}
                  </div>
                </div>

                <div className={style.cardContent}>
                  <div className={style.detailRow}>
                    <span className={style.label}>申请医院:</span>
                    <span className={style.value}>{record.hospital}</span>
                  </div>
                  <div className={style.detailRow}>
                    <span className={style.label}>申请人:</span>
                    <span className={style.value}>{record.applicant || userInfo.name || '未知'}</span>
                  </div>
                  <div className={style.detailRow}>
                    <span className={style.label}>申请时间:</span>
                    <span className={style.value}>{record.applicationTime}</span>
                  </div>
                  <div className={style.detailRow}>
                    <span className={style.label}>订单金额:</span>
                    <span className={style.amount}>¥{record.orderAmount.toFixed(2)}</span>
                  </div>
                </div>

                <div className={style.cardFooter}>
                  {getActionButton(record)}
                </div>
              </div>
            )
          })}
        </div>
      </div>
    </div>
  )
}

export default Index
